/**
 * https://leetcode.cn/problems/merge-two-sorted-lists/?envType=study-plan-v2&envId=top-100-liked
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
//  */
// /**
//  * 递归
//  * @param {ListNode} list1
//  * @param {ListNode} list2
//  * @return {ListNode}
//  */
// var mergeTwoLists = function (list1, list2) {
//   if (!list1) return list2;
//   if (!list2) return list1;
//   let res = list1.val < list2.val ? list1 : list2;
//   res.next = mergeTwoLists(res.next, list1.val >= list2.val ? list1 : list2);
//   return res;
// };

import { ListNode } from "./ListNode.mjs";

/**
 * 迭代
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
  let preHead = new ListNode(-1);
  let pre = preHead;
  while (list1 && list2) {
    if (list1.val <= list2.val) {
      pre.next = list1;
      list1 = list1.next;
    } else {
      pre.next = list2;
      list2 = list2.next;
    }
    pre = pre.next;
  }
  pre.next = list1 == null ? list2 : list1;
  return preHead.next;
};
console.log(mergeTwoLists(new ListNode(1), new ListNode(2)));
